import { ref, watch, inject } from 'vue'
import Configuration from '@/api/client/configuration.js'
import { SURE_TO_DELETE } from '@/constants/message.js'
export function useProjectManager(id, loadConfigurationItems = undefined) {
  const { Modal } = inject('Feedback')
  // PM 候选人
  const projectManagerLoading = ref(true)
  const projectManagerCandidates = ref([])
  Configuration.getProjectManagerCandidates(id).then(({ data }) => {
    projectManagerCandidates.value = data
  })
  const projectManagers = ref([])
  const getGetProjectManagers = () => {
    Configuration.getProjectManagers(id)
      .then(({ data }) => {
        projectManagers.value = data
        // 如果注入了loadConfigurationItems方法，加载完PM需要更新下ConfigurationItems的数据
        if (loadConfigurationItems) {
          loadConfigurationItems()
        }
      })
      .finally(() => {
        projectManagerLoading.value = false
      })
  }
  const handleDeleteProjectManager = userId => {
    Modal.confirm({
      content: SURE_TO_DELETE,
      okButtonProps: { danger: true },
      onOk: () => {
        Configuration.deleteProjectManager(id, userId).then(() => {
          getGetProjectManagers()
        })
      }
    })
  }
  const handleSetPrincipal = userId => {
    Configuration.setProjectManagerPrincipal(id, userId).then(() => {
      getGetProjectManagers()
    })
  }
  getGetProjectManagers()
  const projectManagerCandidatesChoose = ref(null)
  watch(
    () => projectManagerCandidatesChoose.value,
    () => {
      if (projectManagerCandidatesChoose.value) {
        Configuration.addProjectManager(id, projectManagerCandidatesChoose.value).then(() => {
          getGetProjectManagers()
        })
        projectManagerCandidatesChoose.value = null
      }
    }
  )
  return {
    projectManagerCandidates,
    projectManagerCandidatesChoose,
    projectManagers,
    projectManagerLoading,
    handleSetPrincipal,
    handleDeleteProjectManager
  }
}
